package com.example.blackmarket.module.SecondHandTrade.Shoplist;

import android.os.Handler;
import android.util.Log;

import com.example.blackmarket.entities.BuyingShopItem;
import com.example.blackmarket.entities.SellingShopItem;
import com.example.blackmarket.model.BlackMarketApi;
import com.example.blackmarket.callback.IShopCallback;
import com.example.blackmarket.module.Base.BasePresenter;
import com.google.gson.Gson;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class ShoplistPresenter extends BasePresenter<IShoplistView> implements IShopCallback {
    private Handler mHandler;
    public ShoplistPresenter(IShoplistView view) {
        attachView(view);
        mHandler=new Handler();
    }

    //供view调用, 将view的请求转交给model
    public void getData(int pageNo, int typeId){
        String viewName = getView()instanceof SellingFragment?"f1":"f2";
        BlackMarketApi.getShopListData(viewName, pageNo, typeId,new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                mHandler.post(() -> onFail(e.toString()));
            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()){
                    assert response.body() != null;
                    String data = response.body().string();
                    mHandler.post(() -> onSuccess(data));
                }
                else {
                    assert response.body() != null;
                    String msg = "code: "+ response.code() + " body: " +response.body().string();
                    Log.e("response failure",msg);
                    mHandler.post(()->onFail(msg));
                }
            }
        });
    }

    //如果model成功请求到/数据则会回调该方法
    @Override
    public void onSuccess(Object data) {
        if(isViewAttached()) {
            if(this.getView() instanceof SellingFragment) {
                SellingShopItem sellingShopItem = new Gson().fromJson((String) data, SellingShopItem.class);
                this.getView().showData(sellingShopItem);
            }
            else {
                BuyingShopItem buyingShopItem = new Gson().fromJson((String) data, BuyingShopItem.class);
                this.getView().showData(buyingShopItem);
            }
        }
    }

    @Override
    public void onFail(String msg) {
        if(isViewAttached()) {
            this.getView().showToast(msg);
        }
    }

    @Override
    public void onError() {
        //log
    }

    @Override
    public void onComplete() {

    }
}
